<?php

class RegisterFacebookForm extends CFormModel
{
	public $user_id;
	public $facebook_user;
	public function rules()
	{
		return array(
			array('user_id, facebook_user', 'required'),
		);
	}
	
	public function register()
	{
		$transaction = Yii::app()->db->beginTransaction();
		
		try {
			$account = new Account;
			$account->id_type = 'facebook';
			$account->username = $this->facebook_user['username'];
			$account->name = $this->facebook_user['name'];
			$account->facebook = $this->user_id;
				
			if(!$account->save()){
				throw new Exception('Account saving error');
			}
			$detail = new AccountDetail;
			$detail->uid = $account->uid;
			$detail->first_name = $this->facebook_user['first_name'];
			$detail->last_name = $this->facebook_user['last_name'];
				
			if(!$detail->save()){
				throw new Exception('Account Detail saving error');
			}
				
			$facebook = new Facebook;
			$facebook->uid = $account->uid;
			$facebook->fb_id = $this->user_id;
			$facebook->email = $this->facebook_user['email'];
			if(!$facebook->save()){
				throw new Exception('Facebook saving error');
			}
			$transaction->commit();
			return true;
		}
		catch (Exception $e){
			$transaction->rollback();
			Yii::app()->end();
		}
		return false;
	}
}